﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebPortal.Models.ViewModel;
using WebPortal.Models.EntityModels;
using WebPortal.Helpers;

namespace WebPortal.Controllers
{
    public class ProfileController : BaseController
    {
        //
        // GET: /Profile/
        
        public ActionResult Index(UserDetailsModel u)
        {
            UserDetailsModel user;
            if ("GET".Equals(Request.HttpMethod))
            {
                var _user = (from users in dbUsers.Users
                            where users.UserID == User.UserID
                            select users).First();
                user = new UserDetailsModel(_user);
            }
            else
            {
                if (ModelState.IsValid)
                {
                    u.CopyToUser(ref User);
                    dbUsers.SaveChanges();
                }
                user = u;
            }
            return View(user);
        }

        protected bool Validate(UserSecurityModel u)
        {
            bool result = true;
            String hash = MD5.Encrypt(u.OldPassword);
            result &= User.Password.Equals(hash);
            if (u.NewPassword != null && !u.NewPassword.Equals(""))
                result &= u.NewPassword.Equals(u.ConfirmPassword);
            return result;
        }

        public ActionResult Security(UserSecurityModel u)
        {
            ViewData["validate"] = false;
            if ("GET".Equals(Request.HttpMethod))
            {
                var _user = (from users in dbUsers.Users
                             where users.UserID == User.UserID
                             select users).First();
                u = new UserSecurityModel(_user);
            }
            else
            {
                ViewData["validate"] = true;
                if (ModelState.IsValid)
                {
                    if (Validate(u))
                    {
                        u.CopyToUser(ref User);
                        dbUsers.SaveChanges();
                    }
                    else
                    {
                        ViewData["invalid"] = true;
                    }
                }
            }
            return View(u);
        }

    }
}
